﻿Imports FuncClasses
Imports System.Data
Imports System.Windows.Controls.Primitives

Public Class AuftragControl
    Private auftrag As Order
    Private database As IDatabase
    Public WithEvents ribbon As AuftragRibbon
    Private suggestion2 As core.AutoCompleteManager
    Private chooseCustomerforAuftrag As Boolean
    Private chooseArticelforAuftrag As Boolean = False
    Private isloading As Boolean = True
    Private CanMoveArtikelinAuftrag As Boolean = False
    Private _viewmodel As OrderControlViewModel
    Private _user As User
    Private orderviewmodel As OrderViewModel
    Private _window As Window1

    Public Sub New(ByVal _auftrag As Order, ByRef _database As IDatabase, ByRef _ribbon As AuftragRibbon, ByRef settingsvm As VariousSettingsViewModel, ByRef ordervm As OrderViewModel, ByRef window As Window1, user As User)
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        ComboBox10.ItemsSource = settingsvm.PaymentMethodes
        ComboBox11.ItemsSource = settingsvm.OrderTexts
        combobox12.ItemsSource = settingsvm.OrderTexts
        database = _database
        ribbon = _ribbon
        auftrag = _auftrag
        orderviewmodel = ordervm
        _window = window
        _user = user
        If Customer.IsEmpty(auftrag.Customer) = False Then
            Txt_Receiver_header.Text = GetUIString("SelectedCustomer")
        End If
        Me.Resources.MergedDictionaries.Add(Dictionaries.GetOrderControlLocalization)
        DataContext = auftrag

        _viewmodel = New OrderControlViewModel(auftrag)
        ListView1.DataContext = _viewmodel
        CBCustomerAddresses.DataContext = _viewmodel.Order.Customer
        Grid_OrderDeliverAddress.DataContext = _viewmodel
        If Customer.IsEmpty(auftrag.Customer) = False Then
            TabAuftrag.SelectedItem = AuftragArtikel
        End If
        _ribbon._selecteddate = _auftrag.Datum.ToDate
        auftrag.LastEditBy = New nHibernate.Models.UserPreviewModel With {.UserName = _user.Name, .UserID = _user.ID}
    End Sub

    Private Sub Kundedaten_from_Auftrag_to_Auftrag(ByVal CustomerID As String)
        auftrag.Customer = database.GetCustomer(CustomerID, _user)
        With auftrag.Customer
            Txt_Receiver_header.Text = GetUIString("SelectedCustomer")
        End With
        If auftrag.Customer.PaymentMethode IsNot Nothing Then
            If String.IsNullOrEmpty(auftrag.Customer.PaymentMethode.Name) = False Then
                auftrag.PaymentMethode = auftrag.Customer.PaymentMethode
                ComboBox10.SelectedItem = auftrag.Customer.PaymentMethode
            Else
                ComboBox10.SelectedIndex = -1
            End If
        Else
            ComboBox10.SelectedIndex = -1
        End If
        If String.IsNullOrEmpty(TextBox36.Text) Then
            TextBox36.Text = "0,00"
        End If
        CBCustomerAddresses.DataContext = _viewmodel.Order.Customer
        ribbon.Header = auftrag.Customer.DisplayName
        ShowUnsaved()
    End Sub

    Private Sub TabControl_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        With ribbon
            Try
                If Customer.IsEmpty(auftrag.Customer) = False Then
                    .spinner.IsEnabled = False
                    .MIRechnung.IsEnabled = False
                    .MIAngebot.IsEnabled = False
                    .MILieferschein.IsEnabled = False
                    .MIGutschrift.IsEnabled = False
                End If
            Catch ex As Exception
                Log.AddError(ex.ToString)
            End Try
            
            Try
                Select Case auftrag.DokumentArt
                    Case Dokumentart.Angebot
                        .MIAngebot.IsChecked = True
                        RibbonAngebot(False)
                    Case Dokumentart.Gutschrift
                        .MIGutschrift.IsChecked = True
                        RibbonGutschrift(False)
                    Case Dokumentart.Lieferschein
                        .MILieferschein.IsChecked = True
                        RibbonLieferschein(False)
                    Case Dokumentart.Rechnung
                        .MIRechnung.IsChecked = True
                        RibbonRechnung(False)
                End Select
                .spinner.Value = auftrag.OrderID
                .spinner.Foreground = Brushes.Black
                .buttonAuftragSpeichern.IsEnabled = True
                .ButtonDatum.Header = "Datum " + auftrag.Datum.ToString
                TextBox36.Text = Math.Round(auftrag.Rebate * 100, 2).ToString("0.00") + " %"
            Catch ex As Exception
                Log.AddError(ex.ToString)
            End Try
            
        End With

        Try
            If True Then
                With orderviewmodel.AllOrders
                    Dim auf As New OrderPreviewModel
                    auf.OrderTyp = CInt(Dokumentart.Angebot)
                    auf.OrderID = (auftrag.LinkedFromOffer)
                    If .Contains(auf) Then
                        _viewmodel.LinkedOrders.Add(.Item(.IndexOf(auf)))
                    End If
                    auf.OrderID = (auftrag.LinkedToOffer)
                    If .Contains(auf) Then
                        _viewmodel.LinkedOrders.Add(.Item(.IndexOf(auf)))
                    End If

                    auf.OrderTyp = CInt(Dokumentart.Gutschrift)
                    auf.OrderID = (auftrag.LinkedFromCredit)
                    If .Contains(auf) Then
                        _viewmodel.LinkedOrders.Add(.Item(.IndexOf(auf)))
                    End If
                    auf.OrderID = (auftrag.LinkedToCredit)
                    If .Contains(auf) Then
                        _viewmodel.LinkedOrders.Add(.Item(.IndexOf(auf)))
                    End If

                    auf.OrderTyp = CInt(Dokumentart.Rechnung)
                    auf.OrderID = (auftrag.LinkedFromInvoice)
                    If .Contains(auf) Then
                        _viewmodel.LinkedOrders.Add(.Item(.IndexOf(auf)))
                    End If
                    auf.OrderID = (auftrag.LinkedToInvoice)
                    If .Contains(auf) Then
                        _viewmodel.LinkedOrders.Add(.Item(.IndexOf(auf)))
                    End If

                    auf.OrderTyp = CInt(Dokumentart.Lieferschein)
                    auf.OrderID = (auftrag.LinkedFromDelivery)
                    If .Contains(auf) Then
                        _viewmodel.LinkedOrders.Add(.Item(.IndexOf(auf)))
                    End If
                    auf.OrderID = (auftrag.LinkedToDelivery)
                    If .Contains(auf) Then
                        _viewmodel.LinkedOrders.Add(.Item(.IndexOf(auf)))
                    End If
                End With
            End If
        Catch ex As Exception
            Log.AddError(ex.ToString)
        End Try
        Try
            If auftrag.DeliveryAddress IsNot Nothing Then
                buttonAuftragLieferanschrift.IsChecked = False
                Grid_OrderDeliverAddress.Visibility = Windows.Visibility.Visible
            End If
        Catch ex As Exception
            Log.AddError(ex.ToString)
        End Try
        
        isloading = False
    End Sub

    Private Sub RefreshCustomerDataDisplay()
        If Customer.IsEmpty(auftrag.Customer) = False Then
            With auftrag.Customer
                Txt_Receiver_header.Text = GetUIString("SelectedCustomer")
                If .CustomerID = "" AndAlso Customer.IsEmpty(auftrag.Customer) = False Then
                    buttonAuftragKundewählen.Visibility = Windows.Visibility.Visible
                    buttonAuftragKundeEigen.Visibility = Windows.Visibility.Visible
                    buttonAuftragKundeEigen.IsChecked = True
                    TextBox1.Text = .Address.Forname
                    TextBox2.Text = .Address.Surname
                    TextBox3.Text = .Address.Street
                    TextBox4.Text = .Address.No
                    TextBox21.Text = .Address.ZipCode
                    TextBox6.Text = .Address.City
                    TextBox5.Text = .Address.Country
                    TextBox7.Text = .Address.Addition
                ElseIf .CustomerID IsNot "" Then
                End If
            End With
        Else
            Txt_Receiver_header.Text = GetUIString("NoCustomerSelected")
            Txt_Receiver_address.Text = GetUIString("NoAddress")
            buttonAuftragKundewählen.Visibility = Windows.Visibility.Visible
            buttonAuftragKundeEigen.Visibility = Windows.Visibility.Visible
        End If
    End Sub

    Private Sub ShowUnsaved()
        If ribbon.Header.ToString.Contains(" *") = False Then
            ribbon.Header += " *"
        End If
    End Sub

    Private Sub SaveAuftrag()
        '### Check Order ###'
        '### Focus for one textbox each tab ###'
        FocusTBParentForMVVM(TextBox8)
        FocusTBParentForMVVM(TextBoxSalutation)
        FocusTBParentForMVVM(TB_CustomerFastPick)
        FocusTBParentForMVVM(TextBox40)
        If True Then
            ribbon.spinner.IsEnabled = False
            ribbon.MIRechnung.IsEnabled = False
            ribbon.MIAngebot.IsEnabled = False
            ribbon.MILieferschein.IsEnabled = False
            ribbon.MIGutschrift.IsEnabled = False

            orderviewmodel.SaveOrder(auftrag)
            ribbon.Header = ribbon.Header.ToString.Replace(" *", "")
            _window.ReceiveAuftragDataForListView(auftrag)
        End If
    End Sub

    Private Sub ListViewAuftragsArtikel_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListViewAuftragsArtikel.SelectionChanged
        If ListViewAuftragsArtikel.SelectedItems.Count = 1 Then
            Try
                Dim art As OrderedArticle = ListViewAuftragsArtikel.SelectedItem
                SpinnerArtikelPosition.Maximum = auftrag.OrderedArticles.Count
                SpinnerArtikelPosition.Value = art.OrderPosition
                SpinnerArtikelPosition.Minimum = 1
                CanMoveArtikelinAuftrag = True
                ribbon.buttonAuftragArtikellöschen.IsEnabled = True
            Catch ex As Exception
                'Better to do nothing
            End Try
        End If
    End Sub

    Private Sub ListViewAuftragsArtikel_PreviewMouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles ListViewAuftragsArtikel.PreviewMouseDown
        CanMoveArtikelinAuftrag = False
    End Sub

    Private Sub SpinnerArtikelPosition_ValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of System.Double)) Handles SpinnerArtikelPosition.ValueChanged
        If ListViewAuftragsArtikel.SelectedItems.Count = 1 Then
            If CanMoveArtikelinAuftrag Then
                auftrag.OrderedArticles.Move(auftrag.OrderedArticles.IndexOf(ListViewAuftragsArtikel.SelectedItem), SpinnerArtikelPosition.Value - 1)
                For Each art As OrderedArticle In auftrag.OrderedArticles
                    art.OrderPosition = auftrag.OrderedArticles.IndexOf(art) + 1
                Next
                ShowUnsaved()
            End If
        End If
    End Sub

    ''' <summary>
    ''' Auftragspreis
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TextBox9_LostFocus(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles TextBox9.LostKeyboardFocus
        If ListViewAuftragsArtikel.SelectedItem IsNot Nothing Then
            With DirectCast(ListViewAuftragsArtikel.SelectedItem, OrderedArticle)
                Try
                    .OrderPrice = New EMoney(CDec(TextBox9.Text.Replace("€", "").Trim), .OrderPrice.IsGross)
                Catch ex As Exception
                    Log.AddError(ex.ToString)
                End Try
            End With
        End If
    End Sub

    ''' <summary>
    ''' Workaround as it seems, the value is not updated properly
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TextBox8_LostFocus(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles TextBox8.LostKeyboardFocus
        If ListViewAuftragsArtikel.SelectedItem IsNot Nothing Then
            With DirectCast(ListViewAuftragsArtikel.SelectedItem, OrderedArticle)
                Try
                    .OrderedAmount = CDec(TextBox8.Text.Replace(.ArticleUnit.ShortName, "").Trim)
                Catch ex As Exception
                    Log.AddError(ex.ToString)
                    Try
                        .OrderedAmount = CDec(TextBox8.Text.Trim)
                    Catch : End Try
                End Try
            End With
        End If
    End Sub

    ''' <summary>
    ''' Workaround as it seems, the value is not updated properly
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TextBox10_LostFocus(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles TextBox10.LostKeyboardFocus
        If ListViewAuftragsArtikel.SelectedItem IsNot Nothing Then
            With DirectCast(ListViewAuftragsArtikel.SelectedItem, OrderedArticle)
                Try
                    .OrderRebate = CDec(TextBox10.Text.Replace("%", "").Trim)
                Catch ex As Exception
                    Log.AddError(ex.ToString)
                End Try
            End With
        End If
    End Sub

#Region "Eigene Adresse"
    Private Sub TextBox21_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
        If TextBox21.Text.Length = 5 Then
            
        End If
    End Sub
#End Region

    Private Sub buttonAuftragArtikellöschen_Click() Handles ribbon.ArticleDeleteRequest
        If ListViewAuftragsArtikel.SelectedItems.Count = 1 Then
            Dim art As Article = ListViewAuftragsArtikel.SelectedItem
            auftrag.DeleteArticle(art.ArticleID)
            ShowUnsaved()
        End If
    End Sub

    ''' <summary>
    ''' Zahlungsart
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub ComboBox10_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles ComboBox10.SelectionChanged
        If isloading = False Then
            ShowUnsaved()
        End If
    End Sub

    ''' <summary>
    ''' Gesamtrabatt. This is the only textbox, that is not implemented via MVVM
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TextBox36_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox36.TextChanged
        If isloading = False Then
            Try
                Dim dec As Decimal = CDec(TextBox36.Text.Replace("%", "").Trim)
                dec = dec / 100
                auftrag.Rebate = dec
            Catch ex As Exception
                auftrag.Rebate = 0
            End Try
            ShowUnsaved()
        End If
    End Sub

    ''' <summary>
    ''' Fester Abzug
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TextBox40_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox40.TextChanged
        If isloading = False Then
            Try
                auftrag.Reduction = New Money(CDec(TextBox40.Text.Replace("€", "").Trim))
            Catch ex As Exception
                auftrag.Reduction = New Money(0)
            End Try
            ShowUnsaved()
        End If
    End Sub

    Private Sub TextBox41_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox41.TextChanged
        If isloading = False Then
            ShowUnsaved()
        End If
    End Sub

    ' ''' <summary>
    ' ''' Auftragstext
    ' ''' </summary>
    ' ''' <param name="sender"></param>
    ' ''' <param name="e"></param>
    ' ''' <remarks></remarks>
    'Private Sub TextBox37_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox37.TextChanged
    '    If isloading = False Then
    '        ShowUnsaved()
    '    End If
    'End Sub

    ''' <summary>
    ''' Auftragstext Vorlage
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub ComboBox11_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles ComboBox11.SelectionChanged
        If ComboBox11.SelectedIndex > -1 Then
            Dim d As nHibernate.Models.OrderTextModel = ComboBox11.SelectedItem
            auftrag.OrderText = d.Text
        End If
    End Sub

#Region "Auftrag weiterführen"
    Public Event furtherorder(ByVal auf As Order, target As Dokumentart)
    Private Sub AuftragWeiterfuehren(ByVal targetDokument As Dokumentart)
        RaiseEvent furtherorder(auftrag, targetDokument)
    End Sub

    Private Sub FurtherOrder1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles FurtherOrder1.Click
        Select Case auftrag.DokumentArt
            Case Dokumentart.Angebot
                AuftragWeiterfuehren(Dokumentart.Gutschrift)
            Case Dokumentart.Gutschrift
                AuftragWeiterfuehren(Dokumentart.Lieferschein)
            Case Dokumentart.Lieferschein
                AuftragWeiterfuehren(Dokumentart.Rechnung)
            Case Dokumentart.Rechnung
                AuftragWeiterfuehren(Dokumentart.Angebot)
        End Select
    End Sub

    Private Sub ButtonDokument2_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles FurtherOrder2.Click
        Select Case auftrag.DokumentArt
            Case Dokumentart.Angebot
                AuftragWeiterfuehren(Dokumentart.Lieferschein)
            Case Dokumentart.Gutschrift
                AuftragWeiterfuehren(Dokumentart.Rechnung)
            Case Dokumentart.Lieferschein
                AuftragWeiterfuehren(Dokumentart.Angebot)
            Case Dokumentart.Rechnung
                AuftragWeiterfuehren(Dokumentart.Gutschrift)
        End Select
    End Sub

    Private Sub ButtonDokument3_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles FurtherOrder3.Click
        Select Case auftrag.DokumentArt
            Case Dokumentart.Angebot
                AuftragWeiterfuehren(Dokumentart.Rechnung)
            Case Dokumentart.Gutschrift
                AuftragWeiterfuehren(Dokumentart.Angebot)
            Case Dokumentart.Lieferschein
                AuftragWeiterfuehren(Dokumentart.Gutschrift)
            Case Dokumentart.Rechnung
                AuftragWeiterfuehren(Dokumentart.Lieferschein)
        End Select
    End Sub
#End Region

    'Private Sub OwnCustomer() Handles ribbon.OwnCustomerChecked
    '    buttonAuftragKundeEigen.IsChecked = True
    '    GroupAuftragEigeneAdresse.Visibility = Windows.Visibility.Visible
    'End Sub

    'Private Sub OwnCustomerCheckedNonRibbon() Handles buttonAuftragKundeEigen.Checked
    '    ribbon.buttonAuftragKundeEigen.IsChecked = True
    'End Sub

    'Private Sub OwnCustomerUncheckedNonRibbon() Handles buttonAuftragKundeEigen.Unchecked
    '    ribbon.buttonAuftragKundeEigen.IsChecked = False
    'End Sub

    Private Sub Print() Handles ribbon.PrintPDF, ribbon.SaveAsPDFClicked
        FocusTBParentForMVVM(TextBox8)
        FocusTBParentForMVVM(TextBoxSalutation)
        FocusTBParentForMVVM(TB_CustomerFastPick)
        FocusTBParentForMVVM(TextBox40)
    End Sub

    'Private Sub OwnCustomerUnchecked() Handles ribbon.OwnCustomerUnchecked
    '    buttonAuftragKundeEigen.IsChecked = False
    '    GroupAuftragEigeneAdresse.Visibility = Windows.Visibility.Collapsed
    'End Sub

    Public Sub AddRequestedArticle(ByVal _art As Article)
        Dim art As New OrderedArticle(_art)
        If Not String.IsNullOrEmpty(art.ArticleID) Then
            art.OrderedAmount = 1
            art.OrderPosition = auftrag.OrderedArticles.Count + 1
            art.OrderRebate = 0
            art.OrderText = art.ArticleText
            Try
                Select Case auftrag.Customer.Preisgruppe
                    Case Preisgruppe.Preisgruppe1
                        art.OrderPrice = art.ArticlePrice1
                    Case Preisgruppe.Preisgruppe2
                        art.OrderPrice = art.ArticlePrice2
                    Case Preisgruppe.Preisgruppe3
                        art.OrderPrice = art.ArticlePrice3
                End Select
            Catch ex As Exception
                art.OrderPrice = art.ArticlePrice1
            End Try
            art.OrderArticleID = Guid.NewGuid.ToString
            auftrag.OrderedArticles.Add(art)
            TabAuftrag.SelectedIndex = 2

            ListViewAuftragsArtikel.SelectedIndex = ListViewAuftragsArtikel.Items.Count - 1
            ListViewAuftragsArtikel.SelectedItem = (art)
            ShowUnsaved()
        End If
    End Sub

    Public Sub AddRequestedArticle(artnr As String)
        AddRequestedArticle(database.GetArticle(artnr, _user))
    End Sub

    Public Sub AddRequestedCustomer(CustomerNr As String)
        Kundedaten_from_Auftrag_to_Auftrag(CustomerNr)
    End Sub

    Private Sub QuickSave() Handles ribbon.QuickSave, ribbon.SaveAndExit
        SaveAuftrag()
    End Sub

    Private Sub RibbonRechnung(Optional ByVal newNumber As Boolean = True) Handles ribbon.ButtonRechnungChecked
        FurtherOrder1.LargeIcon = "pack://application:,,,/Biller;component/Images/auftraga.png"
        FurtherOrder2.LargeIcon = "pack://application:,,,/Biller;component/Images/auftragg.png"
        FurtherOrder3.LargeIcon = "pack://application:,,,/Biller;component/Images/auftragl.png"
        FurtherOrder1.Header = GetUIString("Offer")
        FurtherOrder2.Header = GetUIString("Credit")
        FurtherOrder3.Header = GetUIString("DeliveryOrder")

        If newNumber AndAlso isloading = False Then
            auftrag.DokumentArt = Dokumentart.Rechnung
            auftrag.OrderID = (_window.NewAuftragsNumber(Dokumentart.Rechnung))
            ribbon.spinner.Value = auftrag.OrderID
        End If
    End Sub

    Private Sub RibbonLieferschein(Optional ByVal newNumber As Boolean = True) Handles ribbon.ButtonLieferscheinChecked
        FurtherOrder1.LargeIcon = "pack://application:,,,/Biller;component/Images/auftragr.png"
        FurtherOrder2.LargeIcon = "pack://application:,,,/Biller;component/Images/auftraga.png"
        FurtherOrder3.LargeIcon = "pack://application:,,,/Biller;component/Images/auftragg.png"
        FurtherOrder1.Header = GetUIString("Invoice")
        FurtherOrder2.Header = GetUIString("Offer")
        FurtherOrder3.Header = GetUIString("Credit")

        If newNumber AndAlso isloading = False Then
            auftrag.DokumentArt = Dokumentart.Lieferschein
            auftrag.OrderID = (_window.NewAuftragsNumber(Dokumentart.Lieferschein))
            ribbon.spinner.Value = auftrag.OrderID
        End If
    End Sub

    Private Sub RibbonAngebot(Optional ByVal newNumber As Boolean = True) Handles ribbon.ButtonAngebotChecked
        FurtherOrder1.LargeIcon = "pack://application:,,,/Biller;component/Images/auftragg.png"
        FurtherOrder2.LargeIcon = "pack://application:,,,/Biller;component/Images/auftragl.png"
        FurtherOrder3.LargeIcon = "pack://application:,,,/Biller;component/Images/auftragr.png"
        FurtherOrder1.Header = GetUIString("Credit")
        FurtherOrder2.Header = GetUIString("DeliveryOrder")
        FurtherOrder3.Header = GetUIString("Invoice")

        If newNumber AndAlso isloading = False Then
            auftrag.DokumentArt = Dokumentart.Angebot
            auftrag.OrderID = (_window.NewAuftragsNumber(Dokumentart.Angebot))
            ribbon.spinner.Value = auftrag.OrderID
        End If
    End Sub

    Private Sub RibbonGutschrift(Optional ByVal newNumber As Boolean = True) Handles ribbon.ButtonGutschriftChecked
        FurtherOrder1.LargeIcon = "pack://application:,,,/Biller;component/Images/auftragl.png"
        FurtherOrder2.LargeIcon = "pack://application:,,,/Biller;component/Images/auftragr.png"
        FurtherOrder3.LargeIcon = "pack://application:,,,/Biller;component/Images/auftraga.png"
        FurtherOrder1.Header = GetUIString("DeliveryOrder")
        FurtherOrder2.Header = GetUIString("Invoice")
        FurtherOrder3.Header = GetUIString("Offer")

        If newNumber AndAlso isloading = False Then
            auftrag.DokumentArt = Dokumentart.Gutschrift
            auftrag.OrderID = (_window.NewAuftragsNumber(Dokumentart.Gutschrift))
            ribbon.spinner.Value = auftrag.OrderID
        End If
    End Sub

    Private Sub SpinnerValueChanged(ByRef value As Integer) Handles ribbon.SpinnerValueChanged
        If isloading = False Then
            If database.OrderExists(ribbon.spinner.Value, auftrag.DokumentArt, _user) Then
                ribbon.spinner.Format = 0
                ribbon.spinner.Foreground = Brushes.Red
            Else
                ribbon.spinner.Foreground = Brushes.Black
                auftrag.OrderID = (ribbon.spinner.Value)
            End If
        End If
    End Sub

    Private Sub GenerateTargetFileName(ByRef s As String) Handles ribbon.SaveAsPDFClicked
        s = auftrag.DokumentArt.ToString + " " + GetUIString("Number") + " " + auftrag.OrderID.ToString
    End Sub

    Public ReadOnly Property CompleteAuftrag As Order
        Get
            Return auftrag
        End Get
    End Property

    Public ReadOnly Property TabControl As TabControl
        Get
            Return TabAuftrag
        End Get
    End Property

    Private Sub DateChanged(datum As Datum) Handles ribbon.AuftragDateChanged
        auftrag.Datum = datum
        ShowUnsaved()
    End Sub

    Public Event UserWantToChooseCustomer(source As AuftragRibbon)
    Private Sub buttonAuftragKundewählen_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonAuftragKundewählen.Click
        RaiseEvent UserWantToChooseCustomer(ribbon)
    End Sub

#Region "Own Customer"
    Private Sub TextBox7_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox7.TextChanged, TextBox5.TextChanged, TextBox6.TextChanged, TextBox21.TextChanged, TextBox4.TextChanged, TextBox3.TextChanged, TextBox2.TextChanged, TextBox1.TextChanged, TextBoxSalutation.TextChanged
        If isloading = False Then
            auftrag.Customer = New Customer()
            With auftrag.Customer
                .SetKundenNummer("")
                .Address.Salutation = TextBoxSalutation.Text
                .Address.Forname = TextBox1.Text
                .Address.Surname = TextBox2.Text
                .Address.Street = TextBox3.Text
                .Address.No = TextBox4.Text
                .Address.ZipCode = TextBox21.Text
                .Address.City = TextBox6.Text
                .Address.Country = TextBox5.Text
                .Address.Addition = TextBox7.Text
                RefreshCustomerDataDisplay()
            End With
        End If
    End Sub
#End Region

    Private Sub TB_CustomerFastPick_KeyDown(sender As System.Object, e As System.Windows.Input.KeyEventArgs) Handles TB_CustomerFastPick.KeyDown
        If e.Key = Key.Enter Then
            If database.CustomerExists(TB_CustomerFastPick.Text, _user) Then
                Kundedaten_from_Auftrag_to_Auftrag(TB_CustomerFastPick.Text)
            End If
        End If
    End Sub

    Private Sub TB_CustomerFastPick_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles TB_CustomerFastPick.TextChanged
        If String.IsNullOrEmpty(TB_CustomerFastPick.Text) Then
            SP_FastPickInfo.Visibility = Windows.Visibility.Collapsed
        Else
            SP_FastPickInfo.Visibility = Windows.Visibility.Visible
            If database.CustomerExists(TB_CustomerFastPick.Text, _user) Then
                TB_FastPickInfo.Text = database.GetCustomer(TB_CustomerFastPick.Text, _user).Address.ToString
            Else
                TB_FastPickInfo.Text = GetUIString("CustomerNoNotAvailable")
            End If
        End If
    End Sub

#Region "Delivery Address"
    Private Sub Deliver_tb_fn_TextChanged(sender As System.Object, e As System.Windows.Controls.TextChangedEventArgs) Handles Deliver_tb.TextChanged, Deliver_tb_fn.TextChanged, Deliver_tb_ad.TextChanged, Deliver_tb_co.TextChanged, Deliver_tb_ci.TextChanged, Deliver_tb_zip.TextChanged, Deliver_tb_hn.TextChanged, Deliver_tb_st.TextChanged, Deliver_tb_ln.TextChanged
        If isloading = False Then
            ShowUnsaved()
        End If
    End Sub

    Private Sub buttonAuftragLieferanschrift_Checked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonAuftragLieferanschrift.Checked
        If isloading = False Then
            Grid_OrderDeliverAddress.Visibility = Windows.Visibility.Collapsed
            auftrag.DeliveryAddress = Nothing
        End If
    End Sub

    Private Sub buttonAuftragLieferanschrift_Unchecked(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles buttonAuftragLieferanschrift.Unchecked
        If isloading = False Then
            Grid_OrderDeliverAddress.Visibility = Windows.Visibility.Visible
            auftrag.DeliveryAddress = New Address
        End If
    End Sub

    Private Sub CBCustomerAddresses_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles CBCustomerAddresses.SelectionChanged
        Dim item As Address = CBCustomerAddresses.SelectedItem
        _viewmodel.Order.DeliveryAddress = item
        _viewmodel.UIRefresh()
    End Sub
#End Region

    Private Function GetUIString(key As String)
        Try
            Return Me.FindResource(key).ToString
        Catch ex As Exception
            Return ""
        End Try
    End Function

    Private Sub FocusTBParentForMVVM(textbox As TextBox)
        Dim ancestor As DependencyObject = textbox.Parent
        While ancestor IsNot Nothing
            Dim element = TryCast(ancestor, UIElement)
            If element IsNot Nothing AndAlso element.Focusable Then
                element.Focus()
                Exit While
            End If
            ancestor = VisualTreeHelper.GetParent(ancestor)
        End While
    End Sub

    Private Sub ListView1_MouseDoubleClick(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs) Handles ListView1.MouseDoubleClick
        If ListView1.SelectedItem IsNot Nothing Then
            If ListView1.SelectedItem.GetType = GetType(OrderPreviewModel) Then
                _window.LoadOrder(_window.Database.GetOrder(CType(ListView1.SelectedItem, OrderPreviewModel).OrderID, CType(ListView1.SelectedItem, OrderPreviewModel).OrderTyp, _user))
            End If
        End If
    End Sub

    Private Sub TabItem_KeyDown(sender As System.Object, e As System.Windows.Input.KeyEventArgs) Handles MyBase.KeyDown
        If Not Keyboard.Modifiers = (ModifierKeys.Alt Or ModifierKeys.Control) Then
            If e.Key = Key.S AndAlso Keyboard.Modifiers = (ModifierKeys.Control Or ModifierKeys.Shift) Then
                ribbon.RequestOrderClosing()
            End If
            If e.Key = Key.S AndAlso Keyboard.Modifiers = ModifierKeys.Control Then
                SaveAuftrag()
            End If
            If e.Key = Key.P AndAlso Keyboard.Modifiers = ModifierKeys.Control Then
                ribbon.RequestPrint()
            End If
            If e.Key = Key.E AndAlso Keyboard.Modifiers = ModifierKeys.Control Then
                ribbon.RequestPDFExport()
            End If
            If e.Key = Key.N AndAlso Keyboard.Modifiers = ModifierKeys.Control Then
                ribbon.RequestAddArticle()
            End If
        End If
    End Sub

#Region "Textbox Focus marking"
    Private Sub TextBox8_GotFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles TextBox8.GotFocus
        Try
            System.Threading.Tasks.Task.Factory.StartNew(Sub()
                                                             System.Threading.Thread.Sleep(150)
                                                             Dispatcher.BeginInvoke(Sub()
                                                                                        If TypeOf ListViewAuftragsArtikel.SelectedItem Is OrderedArticle Then
                                                                                            Try
                                                                                                Dim art As OrderedArticle = ListViewAuftragsArtikel.SelectedItem
                                                                                                Dim txt As String = TextBox8.Text
                                                                                                txt = txt.Replace(" " + art.ArticleUnit.ShortName, "")
                                                                                                TextBox8.Select(TextBox8.Text.IndexOf(txt), txt.Length)
                                                                                            Catch ex As Exception : End Try
                                                                                        End If
                                                                                    End Sub)
                                                         End Sub)

        Catch ex As Exception : End Try
    End Sub

    Private Sub TextBox9_GotFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles TextBox9.GotFocus
        System.Threading.Tasks.Task.Factory.StartNew(Sub()
                                                         System.Threading.Thread.Sleep(150)
                                                         Dispatcher.BeginInvoke(Sub()
                                                                                    Try
                                                                                        Dim txt As String = TextBox9.Text
                                                                                        txt = txt.Replace(" €", "")
                                                                                        TextBox9.Select(TextBox9.Text.IndexOf(txt), txt.Length)
                                                                                    Catch ex As Exception : End Try
                                                                                End Sub)
                                                     End Sub)
    End Sub

    Private Sub TextBox10_GotFocus(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles TextBox10.GotFocus
        System.Threading.Tasks.Task.Factory.StartNew(Sub()
                                                         System.Threading.Thread.Sleep(150)
                                                         Dispatcher.BeginInvoke(Sub()
                                                                                    Try
                                                                                        Dim txt As String = TextBox10.Text
                                                                                        txt = txt.Replace(" %", "")
                                                                                        TextBox10.Select(TextBox10.Text.IndexOf(txt), txt.Length)
                                                                                    Catch ex As Exception : End Try
                                                                                End Sub)
                                                     End Sub)
    End Sub
#End Region

    Private Sub TextBox11_KeyUp(sender As System.Object, e As System.Windows.Input.KeyEventArgs) Handles TextBox11.KeyUp
        If database.ArticleExists(TextBox11.Text, _user) Then
            articlequickaddtt.Visibility = Windows.Visibility.Visible
            Dim article As Article = database.GetArticle(TextBox11.Text, _user)
            articlequickaddtt.Title = article.ArticleDescription
            articlequickaddtt.Text = GetUIString("ArtDetailArtNo") & Chr(9) + article.ArticleID + vbCrLf +
                GetUIString("ArtDetailArticle") & Chr(9) & Chr(9) + article.ArticleDescription + vbCrLf +
                GetUIString("ArtDetailSalesPrice") & Chr(9) + article.ArticlePrice1.ToString
            articlequickaddtt.PlacementTarget = TextBox11
            articlequickaddtt.IsOpen = True
        Else
            articlequickaddtt.IsOpen = False
            articlequickaddtt.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub TextBox11_KeyDown(sender As System.Object, e As System.Windows.Input.KeyEventArgs) Handles TextBox11.KeyDown
        If (e.Key = Key.Enter OrElse e.Key = Key.Tab) AndAlso database.ArticleExists(TextBox11.Text, _user) Then
            AddRequestedArticle(TextBox11.Text)
            TextBox11.Text = ""
            articlequickaddtt.IsOpen = False
        End If
    End Sub

    Private Sub ComboBoxStartingText_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)
        Dim cb = DirectCast(sender, ComboBox)
        If cb.SelectedIndex > -1 Then
            Dim d As nHibernate.Models.OrderTextModel = cb.SelectedItem
            auftrag.TextBefore = d.Text
        End If
    End Sub
End Class
